// Copyright (c) 2021 Presto Labs Pte. Ltd.
// Author: gekim

#pragma once

#include <memory>
#include <optional>
#include <string>
#include <vector>

#include "coin2/exchange/base/symbology/spot_product.h"
#include "coin2/exchange/base/symbology/util.h"
#include "coin2/exchange/okex/symbology/currency.h"

namespace coin2::exchange::okex::symbology {

class OkexProduct : public base::symbology::SpotProduct<OkexCurrency, OkexProduct>,
                    public base::symbology::ProductFromStrMixin<OkexProduct> {
 public:
  typedef SpotProduct<OkexCurrency, OkexProduct> BaseProduct;

  OkexProduct(const OkexCurrency& base, const OkexCurrency& quote)
      : SpotProduct(
            base,
            quote,
            ToOkexNativeProduct(base, quote),
            ToOkexNativeProduct(base, quote),
            base::market::ExchangeType::Okex) {}

 public:
  static std::unique_ptr<OkexProduct> FromNativeStrImpl(
      const std::string& native_product,
      int64_t resolve_timestamp) {
    std::unique_ptr<OkexCurrency> base_ptr;
    std::unique_ptr<OkexCurrency> quote_ptr;
    bool success = ParseOkexNativeProduct(native_product, resolve_timestamp, &base_ptr, &quote_ptr);
    if (success) {
      return std::make_unique<OkexProduct>(*base_ptr, *quote_ptr);
    } else {
      return {};
    }
  }

 private:
  static bool ParseOkexNativeProduct(
      const std::string& product_str,
      int64_t resolve_timestamp,
      std::unique_ptr<OkexCurrency>* base_ptr,
      std::unique_ptr<OkexCurrency>* quote_ptr) {
    using base::symbology::HasValue;

    const std::string& product_str_upper = StringToUpperCopy(product_str);
    std::vector<std::string> splitted;
    splitted = Split(product_str_upper, "-");
    if (splitted.size() != 2) {
      return false;
    }

    *base_ptr = OkexCurrency::FromNativeStrNoThrow(splitted[0], resolve_timestamp);
    *quote_ptr = OkexCurrency::FromNativeStrNoThrow(splitted[1], resolve_timestamp);
    return true;
  }

  static std::string ToOkexNativeProduct(const OkexCurrency& base, const OkexCurrency& quote) {
    using base::market::MarketType;
    std::stringstream ss;
    ss << base.native_currency(MarketType::Spot) << '-' << quote.native_currency(MarketType::Spot);
    auto native_product_str = ss.str();
    return native_product_str;
  }
};

}  // namespace coin2::exchange::okex::symbology
